﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Data.Sql;
using System.Data.SqlClient;

namespace QLKHACHHANG
{
    public partial class frmConnectServer : DevExpress.XtraEditors.XtraForm
    {

        public frmConnectServer()
        {
            InitializeComponent();
            InitControl();
        }

        private void InitControl()
        {
            cbAuth.SelectedIndex = 0;
            tbPass.Properties.ReadOnly = true;
            tbUser.Properties.ReadOnly = true;
        }
        // lay danh sach server va instance              
        private void cbServer_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Index == 1)
            {
                DataTable dt = SqlDataSourceEnumerator.Instance.GetDataSources();
                List<string> lstServerName = new List<string>();
                foreach (DataRow dr in dt.Rows)
                {
                    lstServerName.Add(string.Concat(dr["ServerName"], "\\", dr["InstanceName"]));
                }
                cbServer.Properties.Items.AddRange(lstServerName);
            }
        }
        // lay danh sach cac database
        public static List<string> GetListOfDBNames(string connection)
        {
            List<string> lstDBName = new List<string>();

            using (SqlConnection sqlConn = new SqlConnection(connection))
            {
                sqlConn.Open();
                SqlCommand conn = new SqlCommand();
                conn.Connection = sqlConn;
                conn.CommandText = "sp_databases";
                SqlDataReader sdr = conn.ExecuteReader();
                while (sdr.Read())
                {
                    lstDBName.Add(sdr.GetString(sdr.GetOrdinal("database_name")));
                } 
                sqlConn.Close();     
            }
            return lstDBName;
        }
        private void cbAuth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAuth.SelectedIndex == 0)
            {
                tbUser.Properties.ReadOnly = true;
                tbPass.Properties.ReadOnly = true;
            }
            else
            {
                tbUser.Properties.ReadOnly = false;
                tbPass.Properties.ReadOnly = false;
            }
        }
       
      

        private void btClose_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }       
        private void cbDB_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Index == 1)
            {
                string connectionString;
                if (cbAuth.SelectedIndex == 0)
                {
                    connectionString = "Data source=" + cbServer.Text + ";Integrated Security=True;Connect Timeout=5";
                }
                else
                {
                    connectionString = "Data source=" + cbServer.Text + ";User ID=" + tbUser.Text + ";Password=" + tbPass.Text + ";Connect Timeout=5";
                }
                try
                {
                    cbDB.Properties.Items.AddRange(GetListOfDBNames(connectionString));
                }
                catch (Exception)
                {
                    MessageBox.Show("Không thể tìm thấy danh sách tên CSDL, vui lòng kiểm tra lại các thông số !");
                }
            }
            
        }


        private void btCheck_Click(object sender, EventArgs e)
        {
            if ((cbDB.Text != "") || (cbServer.Text != ""))
            {
                try
                {
                    SqlConnection con = new SqlConnection(getConnectionString());
                    con.Open();
                    con.Close();
                    MessageBox.Show("Kết nối thành công");
                }
                catch
                {
                    MessageBox.Show("Kết nối thất bại");
                }

            }else
            {
                MessageBox.Show("Vui lòng kiểm tra lại thông tin máy chủ và CSDL !");
            }
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            try
            {
                SetConfig.setAppSetting("ConnectionString", getConnectionString());
                MessageBox.Show("Lưu thành công !");
                this.Dispose();
            }
            catch(Exception ex)
            {
                MessageBox.Show("Lưu thông tin vào file cấu hình không thành công ! \n\n" + "Mã lỗi:"+ex.Message);
            }
        }
        //lay chuoi ket noi db
        private string getConnectionString()
        {
            string connectionString;
            if (cbAuth.SelectedIndex == 0)
            {
                connectionString = "Data source=" + cbServer.Text + ";Initial Catalog=" + cbDB.Text + ";Integrated Security=True;Connect Timeout=10";
            }
            else
            {
                connectionString = "Data source=" + cbServer.Text + ";Initial Catalog=" + cbDB.Text + ";User ID=" + tbUser.Text + ";Password=" + tbPass.Text + ";Connect Timeout=10";
            }
            return connectionString;
            
        }

       
    }
}